
var socketio = require("socket.io");
var io;
var guestNumber = 1;
var nickNames = {};
var namesUsed = [];
var currentRoom = {};

exports.listen = function(server){
    io = socketio.listen(server);
    io.set("log level", 1);
    io.sockets.on("connection",function(socket){
        guestNumber = assignGuestName(socket,guestNumber,nickNames,namesUsed);
        joinRoom(socket,"Chatting");

        handleMessageBroadcasting(socket,nickNames);
        handleNameChangeAttemps(socket,nickNames,namesUsed);
        handleRoomJoin(socket);

        socket.on("rooms",function(){
            socket.emit("rooms",io.sockets.manager.rooms);
        });

        socket.on("leave",function(){
            var room = currentRoom[socket.id];
            socket.broadcast.to(room).emit("message",{
                text: "User " + nickNames[socket.id]+" has leaved room: " + room + ".",
                type:"sys"
            });
        });
        handleClientDisconnection(socket,nickNames,namesUsed);
    });
};

function assignGuestName(socket,guestNumber,nickNames,namesUsed){
    var name = "guest"+ guestNumber ;
    nickNames[socket.id] = name;
    socket.emit("nameResult",{
        success:true,
        name:name
    });
    namesUsed.push(name);
    return guestNumber + 1;
}

function joinRoom(socket,room){
    socket.join(room);
    currentRoom[socket.id] = room;
    socket.emit("joinResult",{room:room});
    socket.broadcast.to(room).emit("message",{
        text: nickNames[socket.id]+" has joined " + room + "."
        ,type:"sys"
    });
    var usersInRoom = io.sockets.clients(room);
    if (usersInRoom.length > 1){
        var usersInRoomSummary = "Users Currently in " + room + ": ";
        for(var index in usersInRoom){
            var userSocketId = usersInRoom[index].id;
            if (userSocketId != socket.id){
                if(index > 0){
                    usersInRoomSummary += ", ";
                }
                usersInRoomSummary += nickNames[userSocketId];
            }
        }
        usersInRoomSummary += ".";
        socket.emit("message",{text:usersInRoomSummary,type:"sys"});
    }
}

function handleNameChangeAttemps(socket,nickNames,namesUsed){
    socket.on("nameAttempt", function (name) {
       if(name.indexOf("Guest") == 0){
           socket.emit("nameResult",{
               success:false,
               message:"Names can't begin with ‘Guest’ !"
           });
       }else {
           if(namesUsed.indexOf(name) == -1){
               var previousName = nickNames[socket.id];
               var previousNameIndex = namesUsed.indexOf(previousName);
               namesUsed.push(name);
               nickNames[socket.id] = name;
               delete namesUsed[previousNameIndex];
               socket.emit("nameResult",{
                   success:true,
                   name:name
               });
               socket.broadcast.to(currentRoom[socket.id]).emit("message",{
                   text: previousName + " has change name to " + name  +". "
                   ,type:"sys"
               });
           }else{
               socket.emit("nameResult",{
                   success:false,
                   message:"That name is already in use."
               });
           }
       }
    });
}

function handleMessageBroadcasting(socket,nickNames){
    socket.on("message",function(message){
        socket.broadcast.to(message.room).emit("message",{
            text: nickNames[socket.id] + " : " + message.text
            ,type:"content"
        });
    })
}


function handleRoomJoin(socket){
    socket.on("join",function(room){
        socket.leave(currentRoom[socket.id]);
        joinRoom(socket,room.newRoom);
    });
}

function  handleClientDisconnection(socket,nickNames,namesUsed){
    socket.on("disconnect",function(){
        var nameIndex = namesUsed.indexOf(nickNames[socket.id]);
        var nickName = nickNames[socket.id];
        console.log(nickName);
        console.log(currentRoom[socket.id]);
        socket.broadcast.to(currentRoom[socket.id]).emit("message",{
            text: "User " + nickName + " leaved room " + currentRoom[socket.id]
            ,type:"sys"
        });

        delete  namesUsed[nameIndex];
        delete nickNames[socket.id];

    });
}